package com.wdh.kjs.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.wdh.kjs.R;
import com.wdh.kjs.http.Httpurl;
import com.wdh.kjs.http.response.MyCookieStore;
import com.wdh.kjs.model.JsonModel;
import com.wdh.kjs.model.JsonModel_my;
import com.wdh.kjs.util.ToastUtils;

import org.apache.http.impl.client.DefaultHttpClient;

/**
 * Created by CQH on 2016/4/21.
 */
public class AddBankCardActivity extends BaseTopActivity implements View.OnClickListener{
    private LinearLayout choose_bank;
    private Button add_bankcard_confirm;
    private Intent intent;
    private String partyId;
    private String nickName;

    private EditText add_bankcard_number;
    private EditText add_bankcard_phone;
    private EditText add_bankcard_inputmsg;
    private TextView add_bankcard_nickName;
    private TextView choose_bank_name;
    private String bandCardType;
    private String bankCardNameType;
    private TimeCount time;
    private Button add_bankcard_getmsg;
    private JsonModel_my jsonModel_my;
    private int biaoshi = 0;
    private String zhanghu;
    private String mima;
    private JsonModel jsonModel;

    private char separate= '-';
    private int groupLength = 4;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_bankcard);
        initTopBar("添加银行卡");
        time = new TimeCount(60000*3, 1000);
        SharedPreferences share = getSharedPreferences("logininfo", MODE_PRIVATE);
        partyId = share.getString("loginToken", "");
        nickName = share.getString("nickName","");
        zhanghu = share.getString("zhanghao", "");
        mima = share.getString("mima", "");
        initview();

    }

    private void initview() {
        choose_bank_name = (TextView)findViewById(R.id.choose_bank_name);
        add_bankcard_phone = (EditText) findViewById(R.id.add_bankcard_phone);
        add_bankcard_number = (EditText) findViewById(R.id.add_bankcard_number);
        add_bankcard_number.addTextChangedListener(new EditextWatcher());
        add_bankcard_inputmsg = (EditText) findViewById(R.id.add_bankcard_inputmsg);
        add_bankcard_nickName = (TextView)findViewById(R.id.add_bankcard_nickName);
        add_bankcard_nickName.setText("*" + nickName.substring(1, nickName.length()));
        choose_bank = (LinearLayout) findViewById(R.id.choose_bank);
        choose_bank.setOnClickListener(this);
        add_bankcard_confirm = (Button) findViewById(R.id.add_bankcard_confirm);
        add_bankcard_confirm.setOnClickListener(this);
        add_bankcard_getmsg = (Button)findViewById(R.id.add_bankcard_getmsg);
        add_bankcard_getmsg.setOnClickListener(this);
    }

    private void getBandCardType(String bandCardType){
        switch (bandCardType){
            case "农业银行":bankCardNameType="0";break;
            case "工商银行":bankCardNameType="1";break;
            case "建设银行":bankCardNameType="2";break;
            case "民生银行":bankCardNameType="3";break;
            case "兴业银行":bankCardNameType="4";break;
            case "交通银行":bankCardNameType="5";break;
            case "中信银行":bankCardNameType="6";break;
            case "平安银行":bankCardNameType="7";break;
            case "广发银行":bankCardNameType="8";break;
            case "招商银行":bankCardNameType="9";break;
            case "中国银行":bankCardNameType="10";break;
            case "浦发银行":bankCardNameType="11";break;
            default:break;
        }

        Log.i("msg", bandCardType + bankCardNameType + "bandCardType");

    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.choose_bank:
                intent = new Intent(this,ChooseBankActivity2.class);
                startActivityForResult(intent,0);
                break;
            case R.id.add_bankcard_getmsg:
                if(add_bankcard_phone.getText().toString().equals("")){
                    falseDialogShow("请输入银行预留手机号！");
                }else{
                    time.start();
                    intcode();
                }
                break;
            case R.id.add_bankcard_confirm:
                if(choose_bank_name.getText().toString().equals("")){
                    falseDialogShow("请选择发卡银行！");
                }else if(add_bankcard_number.getText().toString().equals("")){
                    falseDialogShow("请输入银行卡号！");
                }else if(add_bankcard_phone.getText().toString().equals("")){
                    falseDialogShow("请输入银行预留手机号！");
                }else if (biaoshi==0){
                    falseDialogShow("未发送验证码！");
                } else {
                    intweb();
                }
                break;
            default:
                    break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode==0){
            if(resultCode==1){
                bandCardType = data.getStringExtra("bandCardType");
                choose_bank_name.setText(bandCardType);
                getBandCardType(bandCardType);
            }
        }
    }

    private void intweb() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("partyId", partyId);
        params.addBodyParameter("bankCardNameType", bankCardNameType);
        String bankcard_num=add_bankcard_number.getText().toString().replaceAll(String.valueOf(separate), "");
        params.addBodyParameter("bankCardNum", bankcard_num);
        params.addBodyParameter("bankCardPhone", add_bankcard_phone.getText().toString());
        params.addBodyParameter("verificationCode", add_bankcard_inputmsg.getText().toString());

        HttpUtils http = new HttpUtils();
        http.configCookieStore(MyCookieStore.firstCookieStore);
        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_BANKCARD_ADD, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Gson gson = new Gson();
                jsonModel_my = gson.fromJson(responseInfo.result, JsonModel_my.class);

                if(jsonModel_my.getMessageAccept().equals("wrong")){
                    falseDialogShow("短信验证码错误！");
                }else if(jsonModel_my.getMessageAccept().equals("success")){
                    SharedPreferences.Editor editor = getSharedPreferences("logininfo", MODE_PRIVATE).edit();

                    editor.putString("levels", "3");

                    editor.commit();
                    if(jsonModel_my.success){
                        trueDialogShow("添加银行卡成功！");
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                intent = new Intent();
                                finish();
                                intent.setClass(AddBankCardActivity.this, BankCardActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                startActivity(intent);
                            }
                        }, 2000);
                    }else
                        falseDialogShow("添加银行卡失败！");
                }

            }
            @Override
            public void onFailure(HttpException error, String msg) {
                ToastUtils.showShort(getApplicationContext(), "网络异常！");
            }
        });

    }

    private void intcode() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("sendName",nickName);
        params.addBodyParameter("bankCardPhone",add_bankcard_phone.getText().toString());

        final HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST, Httpurl.URL_BANDCARD_SENDMSG, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                Gson gson = new Gson();
                jsonModel = gson.fromJson(responseInfo.result, JsonModel.class);
                DefaultHttpClient zpf = (DefaultHttpClient) http.getHttpClient();
                MyCookieStore.firstCookieStore = zpf.getCookieStore();
                biaoshi = 1;
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                ToastUtils.showShort(AddBankCardActivity.this , "网络异常！");
            }
        });
    }

    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {// 计时完毕
            add_bankcard_getmsg.setText("发送验证码");
            add_bankcard_getmsg.setClickable(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程
            add_bankcard_getmsg.setClickable(false);//防止重复点击
            add_bankcard_getmsg.setText(millisUntilFinished / 1000 + "s后可重新获取");
        }
    }

    private void falseDialogShow(String hint) {
        View dialog = (LinearLayout) getLayoutInflater().inflate(R.layout.view_dialog_false, null);
        Button bt_dialog_false_negative = (Button) dialog.findViewById(R.id.bt_dialog_false_negative);
        Button bt_dialog_false_positive = (Button) dialog.findViewById(R.id.bt_dialog_false_positive);
        TextView tv_dialog_false_hint = (TextView) dialog.findViewById(R.id.tv_dialog_false_hint);
        tv_dialog_false_hint.setText(hint);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(dialog);
        builder.create();
        final AlertDialog dialogShow = builder.show();
        bt_dialog_false_negative.setOnClickListener(new android.view.View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialogShow.dismiss();
            }
        });
        bt_dialog_false_positive.setOnClickListener(new android.view.View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialogShow.dismiss();
//                set_tradePwd_phone.setText("");

            }
        });
    }

    private void trueDialogShow(String hint) {
        View dialog = (LinearLayout) getLayoutInflater().inflate(R.layout.view_dialog_true, null);
        TextView tv_dialog_false_hint = (TextView) dialog.findViewById(R.id.tv_dialog_true_hint);
        tv_dialog_false_hint.setText(hint);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(dialog);
        builder.create();
        final AlertDialog dialogShow = builder.show();

    }


    class EditextWatcher implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String str=add_bankcard_number.getText().toString();
            int oldLength = str.length();
            int oldsection = oldLength/groupLength;
            int index=add_bankcard_number.getSelectionStart();
            boolean isNeedContinue = false;
            for(int i = 1; i <= oldsection; i++){
                if((groupLength+1)*i - 1 < oldLength){
                    if(str.charAt((groupLength+1)*i - 1) != separate){
                        isNeedContinue = true;
                        break;
                    }
                }
            }
            if(isNeedContinue){
                StringBuilder sb =new StringBuilder();
                String temp = str.replaceAll(String.valueOf(separate), "");
                sb.append(temp);
                int newLength = sb.length();
                int section = newLength/groupLength;
                for(int i = 1; i <= section; i++){
                    if((groupLength+1)*i - 1 < sb.length()){
                        sb.insert((groupLength+1)*i - 1, separate);
                    }
                }
                index=sb.length();
                add_bankcard_number.setText(sb);
            }
            add_bankcard_number.setSelection(index);
            if (add_bankcard_number.getText().toString().replaceAll(String.valueOf(separate), "").length()>19){
                falseDialogShow("银行卡位数需小于19位！");
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }
}
